/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONPObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.ContractAgreeDTO;
import org.springblade.modules.admin.entity.BuildingContractPlus;
import org.springblade.modules.admin.entity.ElevatorContract;
import org.springblade.modules.admin.service.IBuildingContractPlusService;
import org.springblade.modules.admin.vo.BuildingContractPlusVO;
import org.springblade.modules.admin.vo.BuildingVO;
import org.springblade.modules.admin.vo.contract.BuildingContractPlusEnums;
import org.springblade.modules.admin.vo.contract.ContractBuildingInfoVo;
import org.springblade.modules.admin.vo.contract.ContractExtVo;
import org.springblade.modules.admin.vo.contract.ElevatorAgreeVo;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.ContractAgree;
import org.springblade.modules.admin.vo.ContractAgreeVO;
import org.springblade.modules.admin.wrapper.ContractAgreeWrapper;
import org.springblade.modules.admin.service.IContractAgreeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 合同协议 控制器
 *
 * @author ysq
 * @since 2025-03-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/contract/agree")
@Api(value = "合同协议", tags = "合同协议接口")
public class ContractAgreeController extends BladeController {

	private final IContractAgreeService contractAgreeService;

	private final IBuildingContractPlusService buildingContractPlusService;

	private final IUserService userService;

	@ApiOperation("协议列表")
	@PostMapping("page")
	public R<IPage<ContractAgreeVO>> page(@RequestBody ContractAgreeDTO contractAgreeDTO) {
		IPage<ContractAgreeVO> page = contractAgreeService.pageList(contractAgreeDTO);
		return R.data(page);
	}


	@ApiOperation("添加维保协议")
	@PostMapping("add")
	public R<Boolean> add(@RequestBody ContractAgree contractAgree) {
		contractAgreeService.add(contractAgree);
		return R.data(true);
	}

	@ApiOperation("修改维保协议")
	@PostMapping("update")
	public R<Boolean> update(@RequestBody ContractAgree contractAgree) {
		contractAgreeService.update(contractAgree);
		return R.data(true);
	}


	@ApiOperation("修改维保协议状态")
	@PostMapping("update/status")
	public R<Boolean> updateStatus(@RequestBody ContractAgree contractAgree) {
		contractAgreeService.updateStatus(contractAgree);
		return R.data(true);
	}


	@ApiOperation("删除")
	@GetMapping("delete")
	public R<Boolean> delete(Long id) {
		contractAgreeService.removeById(id);
		return R.data(true);
	}

	@ApiOperation("详情")
	@GetMapping("detail")
	public R<ContractAgree> detail(Long id) {
		ContractAgree contractAgree = contractAgreeService.getById(id);
		if (contractAgree != null) {
			ContractAgree agree = contractAgreeService.getOne(Wrappers.<ContractAgree>lambdaQuery().eq(ContractAgree::getParentId, contractAgree.getId()).last("limit 1"));
			if (agree != null) {
				contractAgree.setParentContractId(agree.getContractId());
				contractAgree.setParentAgreeNo(agree.getAgreeNo());
				contractAgree.setParentId(agree.getId());
			}
		}
		User user = userService.getById(contractAgree.getMaintainMainUser());
		if (user != null) {
			contractAgree.setUserStatus(user.getStatus());
		}

		BuildingContractPlus serviceOne = buildingContractPlusService.getOne(Wrappers.<BuildingContractPlus>lambdaQuery().eq(BuildingContractPlus::getParentId, contractAgree.getContractId()).last("limit 1"));
		if (serviceOne != null) {
			contractAgree.setHqParentContractId(serviceOne.getId());
			contractAgree.setHpParentAgreeNo(serviceOne.getContractNo());
		}
		return R.data(contractAgree);
	}


	@ApiOperation("电梯的合同和协议列表")
	@GetMapping("getElevatorAgreeList")
	public R<List<ElevatorAgreeVo>> getElevatorAgreeList(Long elevatorId) {
		List<ElevatorAgreeVo> list = contractAgreeService.getElevatorAgreeList(elevatorId);
		return R.data(list);
	}

	@ApiOperation("电梯协议时间")
	@GetMapping("getNotPlan")
	public R<Object> getNotPlan(Long elevatorId) {
		List<ElevatorContract> notPlan = contractAgreeService.getNotPlan(null, elevatorId);
		if (notPlan.size() > 0) {
			return R.data(notPlan.get(0));
		}
		return R.data(null);
	}


	@PostMapping("/down/excel")
	public void downExcel(HttpServletResponse response, @RequestBody ContractAgreeDTO contractAgreeDTO) throws IOException {
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList("协议编号", "客户名称", "协议开始时间", "协议结束时间", "协议附件数", "创建时间", "不停保合同",
				"不停保项目", "电梯数量", "创建人", "审核人", "审核状态", "业务状态");
			rows.add(title);
			List<ContractAgreeVO> list = contractAgreeService.downExcel(contractAgreeDTO);
			for (ContractAgreeVO contractAgreeVO : list) {
				List<String> row = new ArrayList<>();
				row.add(Convert.toStr(contractAgreeVO.getAgreeNo(), ""));
				row.add(Convert.toStr(contractAgreeVO.getCustomerUnitName(), ""));
				row.add(Convert.toStr(DateUtil.format(contractAgreeVO.getBeginTime(), "yyyy-MM-dd HH:mm:ss"), ""));
				row.add(Convert.toStr(DateUtil.format(contractAgreeVO.getEndTime(), "yyyy-MM-dd HH:mm:ss"), ""));
				List<ContractExtVo> contractExt = contractAgreeVO.getContractExt();
				if (contractExt == null) {
					row.add("0");
				} else {
					row.add(Convert.toStr(contractExt.size(), "0"));
				}
				row.add(Convert.toStr(DateUtil.format(contractAgreeVO.getCreateTime(), "yyyy-MM-dd HH:mm:ss"), ""));
				row.add(Convert.toStr(contractAgreeVO.getContractNo() + "-" + getContractExtStatus(contractAgreeVO.getContractExtStatus()), ""));
				row.add(Convert.toStr(contractAgreeVO.getBuildNames(), ""));
				row.add(Convert.toStr(contractAgreeVO.getEleCounts(), "0"));
				row.add(Convert.toStr(contractAgreeVO.getCreateUserName(), ""));
				if (contractAgreeVO.getStatus() == 2 || contractAgreeVO.getStatus() == 3) {
					row.add(Convert.toStr(contractAgreeVO.getCheckUserName(), ""));
				} else {
					row.add(Convert.toStr(""));
				}
				row.add(Convert.toStr(getCheckStatus(contractAgreeVO.getStatus()), ""));
				row.add(Convert.toStr(getAgreeStatus(contractAgreeVO.getAgreeStatus()), ""));
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (
			Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}


	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}


	/**
	 * 获取合同的状态
	 * 合同扩展状态
	 * 1:待续签
	 * 2:已续签
	 * 3:即将到期
	 * 4:已脱保
	 * 5:已作废
	 *
	 * @param status
	 * @return
	 */
	private String getContractExtStatus(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "待续签";
		} else if (status == 2) {
			return "已续签";
		} else if (status == 3) {
			return "即将到期";
		} else if (status == 4) {
			return "已脱保";
		} else if (status == 5) {
			return "已作废";
		} else {
			return "-";
		}
	}


	private String getCheckStatus(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "待审核";
		} else if (status == 2) {
			return "审核通过";
		} else if (status == 3) {
			return "审核不通过";
		} else {
			return "-";
		}
	}

	/**
	 * 协议状态1:待回签2:待审核3:待生效4:待完结5:合同待回签6:合同已回签7:审核不通过8:已终止9:已作废10:已关闭
	 *
	 * @param status
	 * @return
	 */
	private String getAgreeStatus(Integer status) {
		status = Convert.toInt(status, -1);
		if (status == 1) {
			return "待回签";
		} else if (status == 2) {
			return "待审核";
		} else if (status == 3) {
			return "待生效";
		} else if (status == 4) {
			return "待完结";
		} else if (status == 5) {
			return "合同待回签";
		} else if (status == 6) {
			return "合同已回签";
		} else if (status == 7) {
			return "审核不通过";
		} else if (status == 8) {
			return "已终止";
		} else if (status == 9) {
			return "已作废";
		} else if (status == 10) {
			return "已关闭";
		} else {
			return "-";
		}
	}
}
